﻿using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFromMediaPlayerDemo.Interface;
using WinFromMediaPlayerDemo.Provider;
namespace WinFromMediaPlayerDemo.Common
{
    public class SignalrRealService
    {
        /// <summary>
        /// 消息提供器
        /// </summary>
        private IMessageProvider _MessageProvider;
        /// <summary>
        /// 播放器管理提供器
        /// </summary>
        private IWMPMangerProvider _WMPMangerProvider;
        /// <summary>
        /// 播放器实例
        /// </summary>
        private AxWMPLib.AxWindowsMediaPlayer _WMP;
        /// <summary>
        /// SignalR连接实例
        /// </summary>
        private HubConnection _HubConnection;

        /// <summary>
        /// SignalR服务器地址
        /// </summary>
        public string SignalRServer { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="messageProvider">消息提供器</param>
        /// <param name="wMPMangerProvider">播放器管理提供器</param>
        public SignalrRealService(IMessageProvider messageProvider,IWMPMangerProvider wMPMangerProvider,string signlarServerAddress)
        {
            
            this._MessageProvider = messageProvider;
            this._WMPMangerProvider = wMPMangerProvider;
            this._WMP = wMPMangerProvider.WMP;
            this.SignalRServer = signlarServerAddress;
            if(string.IsNullOrEmpty(this.SignalRServer))
            {
                _MessageProvider.Show("SignalR服务器未配置");
            }
        }

        public event EventHandler ServerFileUpdatedEventHander;


        /// <summary>
        /// 初始化SignalR连接
        /// </summary>
        public void InitSignalRConnection()
        {
            _HubConnection = new HubConnection(this.SignalRServer);
            IHubProxy videoHubProxy = _HubConnection.CreateHubProxy("VideoHub");
            _HubConnection.Error += (e) =>
            {
                _MessageProvider.Show($"连接异常：{e.Message}");
            };
            
            //重新加载远程视频列表
            videoHubProxy.On("ReloadRemoteVideoList", () => {
                //_MessageProvider.Show("系统提示", "DFDFDS", MessageType.Error);
            });
            //在服务器文件上传后
            videoHubProxy.On("OnServerFileUpdated", () =>
            {
                Task tk = new Task(() =>
                {
                    ServerFileUpdatedEventHander?.Invoke(this, new EventArgs());
                });
                tk.Start();
            });

            //服务器文件删除后
            videoHubProxy.On("OnServerFileDeleted", (List<string> fileNames) =>
            {
                if(fileNames == null || fileNames.Count <= 0)
                {
                    return;
                }
                _WMPMangerProvider.ActionManager(WMPActionType.Stop);
                _WMPMangerProvider.ClearPlayList();
                string fileSavedDirectory = Global.Default.LocalCacheDirecotry;
                if(string.IsNullOrEmpty(fileSavedDirectory))
                {
                    return;
                }
                int errorCount = 0;
                foreach (var item in fileNames)
                {
                    try
                    {
                        string fullFileName = System.IO.Path.Combine(fileSavedDirectory, item);
                        if(!System.IO.File.Exists(fullFileName))
                        {
                            continue;
                        }
                        System.IO.File.Delete(fullFileName);
                    }
                    catch
                    {
                        errorCount++;
                    }
                }
                if(errorCount != 0)
                {
                    _MessageProvider.Show($"{errorCount}个文件删除失败");
                }
                string[] newlyCacheFiles = FileHandler.GetLocalCacheFileList();
                _WMPMangerProvider.ReloadPlayList(newlyCacheFiles);
                _WMPMangerProvider.ActionManager(WMPActionType.Play);
            });
            _HubConnection.Start();
        }
    }
}
